package com.course.api.controller;

import com.course.api.config.Result.Result;
import com.course.api.config.Result.Results;
import com.course.api.entity.Menu;
import com.course.api.mapper.RoleMenuMapper;
import com.course.api.service.Impl.MenuServiceImpl;
import com.course.api.service.Impl.RoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    MenuServiceImpl menuService;

    @Autowired
    RoleServiceImpl roleService;

    @Autowired
    RoleMenuMapper roleMenuMapper;

    /**
     * 获取菜单信息
     * @param name
     * @return
     */
    @GetMapping("/getTreeMenu")
    public Result getTreeMenu(@RequestParam(defaultValue = "") String name) {
        return Results.success(menuService.selectTreeMenu(name));
    }

    /**
     * 添加菜单
     * @param menu
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Menu menu) {
        return Results.success(menuService.save(menu));
    }

    /**
     * 编辑菜单
     * @param menu
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Menu menu) {
        return Results.success(menuService.updateById(menu));
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result remove(@PathVariable(value = "id") Long id) {
        return Results.success(menuService.removeById(id));
    }

    /**
     * 获取对应角色的路由信息
     * @param userType
     * @return
     */
    @GetMapping("/getRouteList")
    public Result getRouteList(@RequestParam String userType) {
        Long roleId = roleService.selectRoleId(userType);

        List<Long> menuIds = roleMenuMapper.selectByRoleId(roleId);
        List<Menu> menus = menuService.selectTreeMenu("");
        // 对查出的所有菜单针对对应角色进行过滤
        List<Menu> roleMenu = menuService.filterMenu(menus, menuIds);

        return Results.success(roleMenu);
    }
}
